using System;
using System.Collections.Generic;
using System.Linq;
using ExitGames.Client.Photon;
using I2.Loc;
using UnityEngine;

namespace BCW.Friends
{
	public class FriendInfoUI : SelectableButton
	{
		public enum MessageType
		{
			BadLeague = 0,
			BadGameType = 1,
			FullRoom = 2,
			GameTypeChanged = 3,
			RoomDoesntExist = 4,
			BadGameVersion = 5
		}

		private enum ServerActionType
		{
			SendInvite = 0,
			RejectInvite = 1,
			AcceptInvite = 2,
			RemoveFriend = 3
		}

		public static Action OnFriendCountChanged;

		public PlayerInfo pInfo;

		public UILabel status;

		public UILabel gameMode;

		public new UILabel name;

		public UILabel nearYou;

		public UIBasicSprite skin;

		public GameObject onlineSprite;

		public GameObject offlineSprite;

		public GameObject canNotJoin;

		public GameObject inviteOk;

		private UILabel onlineText;

		private UILabel offlineText;

		public GameObject friendsButtons;

		public GameObject invitesButtons;

		public GameObject searchButtons;

		public GameObject joinButton;

		public GameObject inviteButton;

		public GameObject acceptInviteButton;

		public GameObject rejectInviteButton;

		public GameObject removeFriendButton;

		private ServerActionType serverActionType;

		private ServerResponse serverResponse;

		public GameObject newMessages;

		public GameObject NewSticker;

		public GameObject InviteBattleSticker;

		[HideInInspector]
		public bool canBeSelected = true;

		private bool _replaced;

		public static event Action updateInvite;

		public void Init(PlayerInfo playerInfo, uint unreadMesages = 0)
		{
			if (onlineSprite != null && offlineSprite != null)
			{
				if (playerInfo.isOnline)
				{
					onlineSprite.SetActive(true);
					offlineSprite.SetActive(false);
					if (onlineText == null)
					{
						onlineText = onlineSprite.GetComponent<UILabel>();
					}
					onlineText.text = GetGameModeName(BCWServer.GetTypeGameByIdMode(playerInfo.gameMode));
				}
				else
				{
					onlineSprite.SetActive(false);
					offlineSprite.SetActive(true);
					if (offlineText == null)
					{
						offlineText = offlineSprite.GetComponent<UILabel>();
					}
					offlineText.text = ScriptLocalization.Get("Friends/src_Offline");
				}
			}
			if (InviteBattleSticker != null)
			{
				InviteBattleSticker.SetActive(playerInfo.inviteToBattle);
			}
			if (NewSticker != null)
			{
				NewSticker.SetActive(playerInfo.isNew);
			}
			if (newMessages != null)
			{
				newMessages.SetActive(unreadMesages != 0);
			}
			if (!FriendsUIController.instance.TabSearch.findWebPlayer && nearYou != null)
			{
				nearYou.gameObject.SetActive(true);
				nearYou.text = ScriptLocalization.Get("Friends/near_you");
			}
			gameMode.text = GetGameModeName(BCWServer.GetTypeGameByIdMode(playerInfo.gameMode));
			name.text = playerInfo.name;
			if (skin.mainTexture == null || !skin.mainTexture.name.Equals("render_" + playerInfo.skinId))
			{
				skin = skin.ReplaceForCurrentPlatform();
				skin.LoadTextureAndAlphaMask("AtlasShopGuns/", "render_" + playerInfo.skinId);
			}
			pInfo = playerInfo;
			UpdateJoinButton();
		}

		private void Awake()
		{
			FriendsController.OnUpdatePlayerDB += UpdateData;
			FriendsController.OnIdsListsUpdated += UpdateData;
			FriendsUINotification.showErrorOver += EnableAllTabsButtons;
		}

		private void OnDestroy()
		{
			FriendsController.OnUpdatePlayerDB -= UpdateData;
			FriendsController.OnIdsListsUpdated -= UpdateData;
			FriendsUINotification.showErrorOver -= EnableAllTabsButtons;
			if (FriendsController.instance != null)
			{
				FriendsController.instance.RemoveNewStatus(pInfo.playerId);
			}
		}

		private void UpdateData()
		{
			if (pInfo.playerId != null && FriendsController.instance.playerDB.ContainsKey(pInfo.playerId))
			{
				Dictionary<string, uint> countNewMessages = FriendsController.instance.GetCountNewMessages();
				uint unreadMesages = 0u;
				if (countNewMessages.ContainsKey(pInfo.playerId))
				{
					unreadMesages = countNewMessages[pInfo.playerId];
				}
				Init(FriendsController.instance.playerDB[pInfo.playerId], unreadMesages);
			}
		}

		public override void Select(bool select)
		{
			if (selected != select && canBeSelected)
			{
				GetComponentsInChildren<UIWidget>(true).ToList().ForEach(delegate(UIWidget x)
				{
					x.depth += ((!select) ? (-50) : 50);
				});
				GetComponentsInChildren<UIPanel>(true).ToList().ForEach(delegate(UIPanel x)
				{
					x.depth += ((!select) ? (-50) : 50);
				});
				base.Select(select);
				switch (FriendsUIController.currentTab)
				{
				case FriendsUIController.FriendUITab.Friends:
					friendsButtons.SetActive(select);
					break;
				case FriendsUIController.FriendUITab.Invites:
					invitesButtons.SetActive(select);
					break;
				case FriendsUIController.FriendUITab.Search:
					searchButtons.SetActive(select);
					break;
				}
			}
		}

		public void InviteFriend()
		{
			EnableAllTabButtons(FriendsUIController.instance.TabSearch, false);
			EnableButton(inviteButton, false, inviteOk);
			serverActionType = ServerActionType.SendInvite;
			FriendsController.instance.InviteFriend(pInfo.playerId, delegate(ServerResponse response)
			{
				serverResponse = response;
				ShowNotification(serverResponse);
			});
		}

		public void AcceptInvite()
		{
			EnableAllTabButtons(FriendsUIController.instance.TabFriends, false);
			EnableButton(acceptInviteButton, false);
			serverActionType = ServerActionType.AcceptInvite;
			FriendsController.instance.AcceptInvite(pInfo.playerId, delegate(ServerResponse status)
			{
				if (status == ServerResponse.Successful)
				{
					if (FriendInfoUI.updateInvite != null)
					{
						FriendInfoUI.updateInvite();
					}
					selectableButtonController.allButtons.Remove(this);
					UnityEngine.Object.Destroy(base.gameObject);
					selectableButtonController.grid.enabled = true;
					if (OnFriendCountChanged != null)
					{
						OnFriendCountChanged();
					}
				}
				serverResponse = status;
				ShowNotification(serverResponse);
			});
		}

		public void RejectInvite()
		{
			EnableAllTabButtons(FriendsUIController.instance.TabFriends, false);
			EnableButton(rejectInviteButton, false);
			serverActionType = ServerActionType.RejectInvite;
			FriendsController.instance.RejectInvite(pInfo.playerId, delegate(ServerResponse status)
			{
				if (status == ServerResponse.Successful)
				{
					if (FriendInfoUI.updateInvite != null)
					{
						FriendInfoUI.updateInvite();
					}
					selectableButtonController.allButtons.Remove(this);
					UnityEngine.Object.Destroy(base.gameObject);
					selectableButtonController.grid.enabled = true;
				}
				serverResponse = status;
				ShowNotification(serverResponse);
			});
		}

		public void UIRemoveFriend()
		{
			FriendsUIController.instance.friendToRemove = this;
			EnableAllTabButtons(FriendsUIController.instance.TabFriends, false);
			EnableButton(removeFriendButton, false);
			FriendsUIMessageManager.instance.OnRemovePlayer();
		}

		public void UICancelRemove()
		{
			EnableButton(removeFriendButton, true);
		}

		public void RemoveFriend()
		{
			EnableAllTabButtons(FriendsUIController.instance.TabFriends, false);
			EnableButton(removeFriendButton, false);
			serverActionType = ServerActionType.RemoveFriend;
			FriendsController.instance.RemoveFriend(pInfo.playerId, delegate(ServerResponse status)
			{
				if (status == ServerResponse.Successful)
				{
					selectableButtonController.allButtons.Remove(this);
					UnityEngine.Object.Destroy(base.gameObject);
					selectableButtonController.grid.enabled = true;
					if (OnFriendCountChanged != null)
					{
						OnFriendCountChanged();
					}
				}
				serverResponse = status;
				ShowNotification(serverResponse);
			});
		}

		public void StartChat()
		{
			FriendsUIChat.GetInstance().OpenChatWith(pInfo.playerId);
		}

		public void JoinGame()
		{
			FriendsUIMessageManager.instance.searchMessagePanel.ShowLoading();
			int oldTypeGame = pInfo.gameMode;
			EnableButton(joinButton, false, canNotJoin);
			EnableAllTabButtons(FriendsUIController.instance.TabFriends, false);
			FriendsController.instance.RequestPlayerInfo(new List<string> { pInfo.playerId }, delegate
			{
				ConnectToFriend(oldTypeGame);
				if (FriendsUIMessageManager.instance != null)
				{
					FriendsUIMessageManager.instance.searchMessagePanel.HideLoading();
				}
			}, true);
		}

		private bool ConnectToFriend(int oldTypeGame)
		{
			if (!pInfo.isOnline)
			{
				BCWDebug.LogError("LOG: Your friend is offline.");
				return false;
			}
			int num = BCWServer.ComparePhotonVersion(pInfo.photonVersion, settings.verConnectPhoton);
			string format = "LOG: Your version is {0}, Friend version is {1}. Consider your version is {2} .";
			string verConnectPhoton = settings.verConnectPhoton;
			string photonVersion = pInfo.photonVersion;
			object arg;
			switch (num)
			{
			case -1:
				arg = "newer";
				break;
			case 1:
				arg = "older";
				break;
			default:
				arg = "equal";
				break;
			}
			BCWDebug.LogError(string.Format(format, verConnectPhoton, photonVersion, arg));
			if (num == 1)
			{
				if (CheckVersion.instance != null && !CheckVersion.actualVersion)
				{
					CheckVersion.instance.ShowUpdate();
				}
				return false;
			}
			if (oldTypeGame != pInfo.gameMode)
			{
				BCWDebug.LogError("LOG: Your friend has change game type.");
				FriendsUIMessageManager.instance.OnCantJoin(GetStringCantJoin(MessageType.GameTypeChanged));
				EnableButton(joinButton, true, canNotJoin);
				return false;
			}
			if (string.IsNullOrEmpty(pInfo.roomName))
			{
				BCWDebug.LogError("LOG: Friend's room name is null or empty.");
				FriendsUIMessageManager.instance.OnCantJoin(GetStringCantJoin(MessageType.RoomDoesntExist));
				return false;
			}
			RoomInfo roomInfoByName = controllerConnectPhoton.thisScript.GetRoomInfoByName(pInfo.roomName);
			if (roomInfoByName == null)
			{
				BCWDebug.LogError("LOG: Room " + pInfo.roomName + " does not exist.");
				FriendsUIMessageManager.instance.OnCantJoin(GetStringCantJoin(MessageType.RoomDoesntExist));
				EnableButton(joinButton, true, canNotJoin);
				return false;
			}
			if (roomInfoByName.playerCount == roomInfoByName.maxPlayers)
			{
				BCWDebug.LogError("LOG: Room is full.");
				FriendsUIMessageManager.instance.OnCantJoin(GetStringCantJoin(MessageType.FullRoom));
				EnableButton(joinButton, true, canNotJoin);
				return false;
			}
			TypeGame typeGameByIdMode = BCWServer.GetTypeGameByIdMode(pInfo.gameMode);
			if (typeGameByIdMode != TypeGame.tanks && typeGameByIdMode != TypeGame.race && typeGameByIdMode != TypeGame.RocketLeague)
			{
				Hashtable customProperties = roomInfoByName.customProperties;
				int num2 = Convert.ToInt32(customProperties[controllerConnectPhoton._minLeague]);
				int num3 = Convert.ToInt32(customProperties[controllerConnectPhoton._maxLeague]);
				if (CupsManager.CurrentTier <= num3 && CupsManager.CurrentTier >= num2)
				{
					BCWDebug.LogError(string.Format("LOG: Connecting to friend to {0} game mode in room {1}.", typeGameByIdMode, pInfo.roomName));
					controllerConnectPhoton.thisScript.joinRoomName(pInfo.roomName);
					return true;
				}
				BCWDebug.LogError("LOG: Your league boiler doesn't match friend's boiler.");
				FriendsUIMessageManager.instance.OnCantJoin(GetStringCantJoin(MessageType.BadLeague));
				EnableButton(joinButton, true, canNotJoin);
				return false;
			}
			switch (typeGameByIdMode)
			{
			case TypeGame.RocketLeague:
				if (roomInfoByName.customProperties.ContainsKey("Boiler") && !roomInfoByName.customProperties["Boiler"].Equals(controllerConnectPhoton.thisScript.CarBoiler[settings.RaceCarName]))
				{
					FriendsUIMessageManager.instance.OnCantJoin(GetStringCantJoin(MessageType.BadLeague));
					EnableButton(joinButton, true, canNotJoin);
					return false;
				}
				BCWDebug.LogError(string.Format("LOG: Connecting to friend to {0} game mode in room {1}.", typeGameByIdMode, pInfo.roomName));
				controllerConnectPhoton.thisScript.joinRoomName(pInfo.roomName);
				return true;
			case TypeGame.tanks:
			{
				BCWDebug.LogError(string.Format("LOG: Connecting to friend to {0} game mode in room {1}.", typeGameByIdMode, pInfo.roomName));
				string text = Load.LoadString("car");
				if (string.IsNullOrEmpty(text) || MarketController.Instance.GetProduct(text).subCategoryName != "Tanks")
				{
					settings.SelectedTankName = "_CarTankFree";
				}
				else
				{
					settings.SelectedTankName = text;
				}
				controllerConnectPhoton.thisScript.joinRoomName(pInfo.roomName);
				return true;
			}
			default:
				BCWDebug.LogError(string.Format("LOG: Won't connect to {0} game mode.", typeGameByIdMode));
				EnableButton(joinButton, true, canNotJoin);
				return false;
			}
		}

		private void UpdateJoinButton()
		{
			TypeGame typeGameByIdMode = BCWServer.GetTypeGameByIdMode(pInfo.gameMode);
			if (!pInfo.isOnline || typeGameByIdMode == TypeGame.Lobby || typeGameByIdMode == TypeGame.normal || typeGameByIdMode == TypeGame.race || BCWServer.ComparePhotonVersion(pInfo.photonVersion, settings.verConnectPhoton) == -1)
			{
				EnableButton(joinButton, false, canNotJoin);
			}
			else
			{
				EnableButton(joinButton, true, canNotJoin);
			}
		}

		private void UpdateInviteButton(ServerResponse serverResponse)
		{
			if (serverResponse == ServerResponse.ServerFail)
			{
				EnableButton(inviteButton, true, inviteOk);
			}
		}

		private void ShowNotification(ServerResponse response)
		{
			string errorMsg = string.Empty;
			if (serverActionType == ServerActionType.SendInvite)
			{
				switch (response)
				{
				case ServerResponse.Successful:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_InviteSuccessful");
					break;
				case ServerResponse.EntityExists:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_InviteExists");
					break;
				case ServerResponse.ServerFail:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_ServerFail");
					break;
				default:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_InternalError");
					break;
				}
			}
			else if (serverActionType == ServerActionType.AcceptInvite)
			{
				switch (response)
				{
				case ServerResponse.Successful:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_AcceptInviteSuccessful");
					break;
				case ServerResponse.ServerFail:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_ServerFail");
					break;
				default:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_InternalError");
					break;
				}
			}
			else if (serverActionType == ServerActionType.RejectInvite)
			{
				switch (response)
				{
				case ServerResponse.Successful:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_RejectInviteSuccessful");
					break;
				case ServerResponse.ServerFail:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_ServerFail");
					break;
				default:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_InternalError");
					break;
				}
			}
			else if (serverActionType == ServerActionType.RemoveFriend)
			{
				switch (response)
				{
				case ServerResponse.Successful:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_RemoveFriendSuccessful");
					break;
				case ServerResponse.ServerFail:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_ServerFail");
					break;
				default:
					errorMsg = ScriptLocalization.Get("Friends/src_Notification_InternalError");
					break;
				}
			}
			FriendsUINotification.instance.AddInQueueWarninMsg(errorMsg);
		}

		private void UpdateAcceptInviteButton(ServerResponse serverResponse)
		{
			if (serverResponse == ServerResponse.ServerFail)
			{
				EnableButton(acceptInviteButton, true);
			}
		}

		private void UpdateRejectInviteButton(ServerResponse serverResponse)
		{
			if (serverResponse == ServerResponse.ServerFail)
			{
				EnableButton(rejectInviteButton, true);
			}
		}

		private void UpdateRemoveFriendButton(ServerResponse serverResponse)
		{
			if (serverResponse == ServerResponse.ServerFail)
			{
				EnableButton(removeFriendButton, true);
			}
		}

		private void EnableAllTabButtons(FriendsUICategory buttonsTab, bool setEnabled)
		{
			buttonsTab.allButtons.ForEach(delegate(SelectableButton x)
			{
				(x as FriendInfoUI).canBeSelected = setEnabled;
			});
		}

		private void EnableAllTabsButtons()
		{
			if (!(FriendsUIController.instance == null))
			{
				switch (serverActionType)
				{
				case ServerActionType.SendInvite:
					UpdateInviteButton(serverResponse);
					break;
				case ServerActionType.RejectInvite:
					UpdateRejectInviteButton(serverResponse);
					break;
				case ServerActionType.AcceptInvite:
					UpdateAcceptInviteButton(serverResponse);
					break;
				case ServerActionType.RemoveFriend:
					UpdateRemoveFriendButton(serverResponse);
					break;
				}
				EnableAllTabButtons(FriendsUIController.instance.TabFriends, true);
				EnableAllTabButtons(FriendsUIController.instance.TabSearch, true);
			}
		}

		private void EnableButton(GameObject button, bool setEnabled, GameObject disabledButton = null)
		{
			if (!(button == null))
			{
				if (disabledButton != null)
				{
					disabledButton.SetActive(!setEnabled);
					button.SetActive(setEnabled);
				}
				else if (setEnabled)
				{
					button.SetActive(setEnabled);
				}
				button.GetComponent<UIButton>().isEnabled = setEnabled;
			}
		}

		public static string GetGameModeName(TypeGame typeGame)
		{
			TypeGame typeGame2 = typeGame;
			if (typeGame2 == TypeGame.Lobby)
			{
				return ScriptLocalization.Get("Friends/src_Lobby");
			}
			if (typeGame == TypeGame.normal)
			{
				typeGame = TypeGame.Offline;
			}
			if (typeGame == TypeGame.OnlineSandbox)
			{
				typeGame = TypeGame.normal;
			}
			GameModeConfig gameModeConfig = GameModeManager.GameModeConfig;
			if (gameModeConfig != null)
			{
				foreach (GameModeConfig.ModeInfo item in gameModeConfig.ModesConfig)
				{
					if (item.typeGame == typeGame)
					{
						return item.GetTranslateName()[LocalizationManager.CurrentLanguage];
					}
				}
			}
			return "Unknown";
		}

		public static string GetStringCantJoin(MessageType messageType)
		{
			string empty = string.Empty;
			switch (messageType)
			{
			case MessageType.BadLeague:
				empty = ScriptLocalization.Get("Friends/bad_league");
				if (string.IsNullOrEmpty(empty))
				{
					empty = "Your league doesn't match friend's league";
				}
				break;
			case MessageType.FullRoom:
				empty = ScriptLocalization.Get("Friends/full_room");
				if (string.IsNullOrEmpty(empty))
				{
					empty = "Room is full";
				}
				break;
			case MessageType.GameTypeChanged:
				empty = ScriptLocalization.Get("Friends/room_changed");
				if (string.IsNullOrEmpty(empty))
				{
					empty = "Your friend just changed type of the game";
				}
				break;
			case MessageType.RoomDoesntExist:
				empty = ScriptLocalization.Get("Friends/room_not_found");
				if (string.IsNullOrEmpty(empty))
				{
					empty = "Room does not exist";
				}
				break;
			case MessageType.BadGameType:
				empty = ScriptLocalization.Get("Friends/bad_game_type");
				if (string.IsNullOrEmpty(empty))
				{
					empty = "You can not connect to that game type";
				}
				break;
			case MessageType.BadGameVersion:
				empty = ScriptLocalization.Get("Friends/bad_game_version");
				if (string.IsNullOrEmpty(empty))
				{
					empty = "Your game version does not match friend's version";
				}
				break;
			default:
				empty = "Неизвестная причина отказа";
				break;
			}
			return empty;
		}

		public static int Compare(FriendInfoUI first, FriendInfoUI second)
		{
			PlayerInfo playerInfo = first.pInfo;
			PlayerInfo playerInfo2 = second.pInfo;
			if (playerInfo.isOnline && !playerInfo2.isOnline)
			{
				return -1;
			}
			if (!playerInfo.isOnline && playerInfo2.isOnline)
			{
				return 1;
			}
			if (playerInfo.isOnline && playerInfo2.isOnline)
			{
				return playerInfo.name.CompareTo(playerInfo2.name);
			}
			return playerInfo.name.CompareTo(playerInfo2.name);
		}
	}
}
